<template>
    <section>
        <!--工具条-->

        <div class="section-content clearfix">
            <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
                <el-form :inline="true" :model="filters">
                    <el-form-item style="float: left;">
                        <el-input v-model="filters.name" placeholder="数据点名称"></el-input>
                    </el-form-item>
                    <el-form-item class="tool-bt">
                        <el-button :type="buttonColor" v-on:click="getUsers()">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <router-link v-if="menubt.indexOf('/device_data_recipe/add_body') > -1" to="/template/adds">
                            <el-button :type="buttonColor">新增</el-button>
                        </router-link>

                        <el-button :type="buttonColor" :loading="addLoading" @click="download">下载模板</el-button>

                        <!-- <el-button :type="buttonColor" :loading="addLoading" @click="rank">修改排序</el-button> -->
                        <!-- <el-upload v-if="menubt.indexOf('/device_data_recipe/add_body')>-1" style="display: inline;"
                            :headers="fileList" multiple :limit="1" :on-exceed="handleExceed"
                            action="/api/auth/excel/import_recipe_tpl" accept=".xls,.xlsx"
                            :on-success="handlexlsSuccess" :before-upload="beforexlsUpload">

                            <el-button size="small" :type="buttonColor">批量上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传xls和pxlsx文件，且不超过5MB</div>


                        </el-upload> -->
                        <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" ref="upload"
                            accept=".xls,.xlsx" :on-change="upload" :show-file-list="false" :auto-upload="false"
                            style="display: inline;">
                            <el-button :type="buttonColor">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-col>

            <!--列表-->
            <el-table :data="hande_device_list" highlight-current-row v-loading="listLoading"
                :header-row-style="{ backgroundColor: titleColor }" @selection-change="selsChange" style="width: 100%;">
                <el-table-column type="selection">
                </el-table-column>
                <el-table-column type="index" label="序号" width="80">
                </el-table-column>
                <el-table-column prop="name" label="数据点名称">
                </el-table-column>
                <el-table-column label="数据类型" prop="dataTypeText">
                </el-table-column>
                <!-- <el-table-column align="center" label="排序值">
                    <template scope="scope">
                        <el-input v-model="scope.row.priority" type="number" placeholder="排序值"></el-input>
                    </template>
                </el-table-column> -->
                <el-table-column prop="register" label="数据点地址">

                </el-table-column>
                <el-table-column prop="registerDefaultValue" label="数据点默认值"></el-table-column>
                <el-table-column prop="valueKindText" label="数值类型">
                </el-table-column>

                <!-- <el-table-column prop="decimalAccuracy" label="小数位数">
                </el-table-column> -->
                <el-table-column prop="unit" label="单位">
                </el-table-column>
                <!-- <el-table-column prop="formula" label="公式">
                </el-table-column> -->
                <!-- <el-table-column  label="数据点限制">
                    <template scope="scope">
                        <span v-if="scope.row.dataRestrict==0">公开</span>
                        <span v-if="scope.row.dataRestrict==1">一级</span>
                        <span v-if="scope.row.dataRestrict==2">二级</span>
                        <span v-if="scope.row.dataRestrict==3">三级</span>
                        <span v-if="scope.row.dataRestrict==4">四级</span>
                        <span v-if="scope.row.dataRestrict==5">五级</span>
                        <span v-if="scope.row.dataRestrict==6">六级</span>
                        <span v-if="scope.row.dataRestrict==7">七级</span>
                        <span v-if="scope.row.dataRestrict==8">八级</span>
                        <span v-if="scope.row.dataRestrict==9">九级</span>
                        <span v-if="scope.row.dataRestrict==10">十级</span>
                        <span v-if="scope.row.dataRestrict==11">不公开</span>
                    </template>
                </el-table-column> -->
                <el-table-column prop="ifVisible" label="是否展示" :formatter="formatifVisible">
                </el-table-column>
                <el-table-column prop="updateTime" label="更新时间" width="180">
                </el-table-column>
                <el-table-column align="center" label="排序">
                    <template scope="scope">
                        <el-button size="mini" @click="gettop(scope.$index, scope.row)" title="置顶" plain><img class="up-img"
                                src="../../assets/8a542d43248d7f6a36e39ef0727858f.png"></el-button>
                        <el-button size="mini" icon="el-icon-arrow-up" @click="gettop1(scope.$index, scope.row)" title="上移"
                            plain></el-button>
                        <el-button size="mini" @click="getdown(scope.$index, scope.row)" title="置底" plain><img
                                class="up-img" src="../../assets/761bc582cd35f1b90c28d8f2a080854.png"></el-button>
                        <el-button size="mini" icon="el-icon-arrow-down" @click="getdown1(scope.$index, scope.row)"
                            title="下移" plain></el-button>
                        <!-- <i class="el-icon-arrow-up"  @click="gettop(scope.$index, scope.row)" title="置顶" style="cursor: pointer;"></i>
                            <i class="el-icon-arrow-down" @click="getdown(scope.$index, scope.row)" title="置底" style="cursor: pointer;"></i> -->
                        <!-- <el-button :type="buttonColor" @click="gettop(scope.$index, scope.row)" style="margin-bottom: 5px;padding: 2px 8px">置顶</el-button>
                        <el-button :type="buttonColor" @click="getdown(scope.$index, scope.row)" style="padding: 2px 8px" plain>置底</el-button> -->
                    </template>
                </el-table-column>
                <el-table-column label="告警规则">
                    <template scope="scope">
                        <el-button size="mini" @click="alarms(scope.$index, scope.row)">规则</el-button>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="操作">
                    <template scope="scope">
                        <i v-if="menubt.indexOf('/device_data_recipe/put_body') > -1"
                            @click="handleEdit(scope.$index, scope.row)" title="编辑" icon="el-icon-edit" circle
                            class="pb-icon icon-edit"></i>
                        <i v-if="menubt.indexOf('/device_data_recipe/delete_body') > -1"
                            @click="handleDel(scope.$index, scope.row)" icon="el-icon-delete" circle title="删除"
                            class="pb-icon icon-delete"></i>

                    </template>
                </el-table-column>
            </el-table>

            <!--工具条-->
            <el-col :span="24" class="toolbar">
                <el-button v-if="menubt.indexOf('/device_data_recipe/delete_body') > -1" type="danger" @click="batchRemove"
                    :disabled="this.sels.length === 0">批量删除</el-button>
                <!-- <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total"
                    style="float:right;">
                </el-pagination> -->
            </el-col>
        </div>
        <!--编辑界面-->
        <el-dialog title="编辑" v-show="editFormVisible" v-model="editFormVisible" :custom-class="dialogTitleColor"
            @close="editFormVisible = false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                    <el-form-item label="模板名称" prop="name">
                        <el-input v-model="editForm.name" auto-complete="off"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="editFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="editSubmit" :loading="editLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" v-show="addFormVisible" v-model="addFormVisible" :custom-class="dialogTitleColor"
            @close="addFormVisible = false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
                    <el-form-item label="名字" prop="name">
                        <el-input v-model="addForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电话号码" prop="name">
                        <el-input v-model="addForm.phone" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="email" prop="name">
                        <el-input v-model="addForm.email" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="微信" prop="name">
                        <el-input v-model="addForm.weixin" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" v-model="addForm.remark"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align: right;">
                    <el-button @click.native="addFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="addSubmit" :loading="addLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
    </section>
</template>

<script>
// import util from './../common/js/util'
//import NProgress from 'nprogress'
import XLSX from 'xlsx'

import {
    device_data_recipe_get,
    device_data_recipe_put,
    alarms_post_user,
    alarms_delete_user,
    device_data_recipe_list_body,
    device_data_recipe_delete_body,
    device_data_recipe_top,
    device_data_recipe_down,
    device_data_recipe_orderby,
    device_data_recipe_add_body,
    unit_query,
    dict_query
} from '../../api/api';

export default {
    data() {
        return {
            fileList: {
                id: sessionStorage.getItem('deviceDataRecipeId'),
                token: JSON.parse(localStorage.getItem('key'))
            },
            edit: '',
            filters: {//名称查询
                name: ''
            },
            query: [],
            total: 0,
            page: 1,
            listLoading: false,
            sels: [], //列表选中列

            editFormVisible: false, //编辑界面是否显示
            editLoading: false,
            editFormRules: {
                name: [{
                    required: true,
                    message: '请输入姓名',
                    trigger: 'blur'
                }, { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }]
            },
            //编辑界面数据
            editForm: {
                id: '',
                name: '',

            },

            addFormVisible: false, //新增界面是否显示
            addLoading: false,
            addFormRules: {
                name: [{
                    required: true,
                    message: '请输入姓名',
                    trigger: 'blur'
                }, { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                path: [{
                    required: true,
                    message: '请输入path',
                    trigger: 'blur'
                }

                ]
            },
            //新增界面数据
            addForm: {
                name: '',
                phone: '',
                email: '',
                weixin: '',
                remark: ''
            },
            bodyList: [],
            hande_device_list: [],
            unitlist: '',
            dictlist: '',
            custom_version: this.CustomVersion()
        }
    },
    computed: {
        city: function () {
            // 通过vuex的getters方法来获取state里面的数据

            return this.$store.getters.getCityFn;
        },
        buttonColor() {
            return this.$store.state.buttonColor
        },
        titleColor() {
            return this.$store.state.titleColor
        },
        dialogTitleColor() {
            return this.$store.state.dialogTitleColor
        },
    },
    methods: {
        search() {//列表渲染和搜索
            this.hande_device_list = [];
            for (let i in this.query) {
                if (this.query[i].name.indexOf(this.filters.name) >= 0) {
                    // if (this.query[i].register.indexOf(this.selectlist.register) >= 0) {
                    // console.log(this.query[i])
                    this.hande_device_list.push(this.query[i]);

                    // }
                }

            }

            this.total = this.hande_device_list.length;//长度
            // this.total = this.device_list.length;

            // this.selectget();
        },
        rank() {//排序
            this.bodyList = [];
            for (let i in this.query) {
                this.bodyList.push({
                    bodyId: this.query[i].id,
                    priority: this.query[i].priority
                })
            }
            let deviceDataRecipeId = sessionStorage.getItem('deviceDataRecipeId');
            let para = {
                dataId: deviceDataRecipeId,
                bodyList: this.bodyList
            }
            device_data_recipe_orderby(para).then((res) => {
                this.begCode(res.code, res.message);
                // this.total = res.data.totalCount;
                this.getUsers()
                //NProgress.done();
            });
        },
        gettop1(index, row) {//上移
            let para = Object.assign({}, row);
            if (this.hande_device_list[index - 1]) {
                let num = row.priority;//当前
                row.priority = this.hande_device_list[index - 1].priority;//上一个下标
                this.hande_device_list[index - 1].priority = num;
                this.rank()
            }
        },
        getdown1(index, row) {//下移
            let para = Object.assign({}, row);
            if (this.hande_device_list[index + 1]) {
                let num = row.priority;
                row.priority = this.hande_device_list[index + 1].priority;
                this.hande_device_list[index + 1].priority = num;
                this.rank()
            }
        },
        gettop(index, row) {//置顶

            if (this.hande_device_list[index - 1]) {
                row.priority = this.hande_device_list[0].priority - 1;
                this.rank()
            }
            return false;
            let deviceDataRecipeId = sessionStorage.getItem('deviceDataRecipeId');
            let para = {
                id: deviceDataRecipeId,
                bodyId: row.id

            };
            //NProgress.start();

            console.log(para)
            device_data_recipe_top(para).then((res) => {
                this.begCode(res.code, res.message);
                // this.total = res.data.totalCount;
                this.getUsers()
                //NProgress.done();
            });
        },
        getdown(index, row) {//置底
            if (this.hande_device_list[index + 1]) {
                row.priority = this.hande_device_list[this.hande_device_list.length - 1].priority + 1;
                this.rank()
            }
            return false;
            let deviceDataRecipeId = sessionStorage.getItem('deviceDataRecipeId');
            let para = {
                id: deviceDataRecipeId,
                bodyId: row.id

            };
            //NProgress.start();

            console.log(para)
            device_data_recipe_down(para).then((res) => {
                this.begCode(res.code, res.message);
                // this.total = res.data.totalCount;
                this.getUsers()
                //NProgress.done();
            });
        },
        download() {//下载模版
            // window.location.href = "https://" + location.host + "/数据模板模板.xls"
            if (this.custom_version == 0) {
                // window.location.href = "https://" + location.host + "/数据配方模板.xls"
                var filename = "数据配方模板.xls";
                var a = document.createElement('a');
                a.href = "/static/shujupeifangmuban.xls";
                a.download = filename;
                a.click()
            } else if (this.custom_version == 2) {//custom_version=2,电量定制
                var filename = "数据配方模板.xls";
                var a = document.createElement('a');
                a.href = "/static/shujuceshimoban1.xls";
                a.download = filename;
                a.click()
                // window.location.href = "https://" + location.host + "/数据配方模板1.xls"
            }
        },
        handlexlsSuccess(res, file) {
            this.begCode(res.code, res.message)
            if (res.code == 0) {

                this.listLoading = false;
                //NProgress.done();
                this.$message({
                    message: '添加成功',
                    type: 'success'
                });
                this.getUsers();

            }
            // this.form.devicePictureList[0].path = res.data.path;
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件`);
        },
        beforexlsUpload(file) {
            let tp = true;
            const isLt2M = file.size / 1024 / 1024 < 5;

            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
            }
            return tp && isLt2M;
        },
        //性别显示转换
        formatSex: function (row, column) {
            return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
        },
        formatifVisible(row, column) {
            return row.ifVisible == 0 ? '不展示' : row.ifVisible == 1 ? '展示' : '未知';
        },
        handleCurrentChange(val) {
            this.page = val;
            this.getUsers();
        },
        //获取菜单列表
        getUsers() {
            if (this.menubt.indexOf('/device_data_recipe/list_body') == -1) {
                this.$message({
                    message: '您没有查询模板内容的权限',
                    type: 'warning'
                });
                return false;
            }
            let deviceDataRecipeId = sessionStorage.getItem('deviceDataRecipeId');
            let para = {
                deviceDataRecipeId: deviceDataRecipeId,

            };
            this.listLoading = true;
            //NProgress.start();


            device_data_recipe_list_body(para).then((res) => {
                this.begCode(res.code, res.message);
                // this.total = res.data.totalCount;
                this.query = res.data.list;

                this.listLoading = false;
                this.search()
                //NProgress.done();
            });
        },
        //删除
        handleDel: function (index, row) {
            this.$confirm('确认删除该数据点吗?', '提示', {
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                //NProgress.start();
                let para = {
                    idList: [row.id],
                    dataId: sessionStorage.getItem('deviceDataRecipeId')
                };
                device_data_recipe_delete_body(para).then((res) => {
                    this.begCode(res.code, res.message);
                    if (res.code == 0) {

                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();

                    }
                });
            }).catch(() => {

            });
        },
        //显示编辑界面
        handleEdit: function (index, row) {
            sessionStorage.setItem('bodyId', row.id);
            this.$router.push({
                path: "/template/edits"
            });
            this.editFormVisible = true;
            this.editForm = Object.assign({}, row);
        },
        //显示新增界面
        handleAdd: function () {

            sessionStorage.setItem('bodyId', row.id);

            this.$router.push({
                path: "/template/adds"
            });

        },
        //编辑
        editSubmit: function () {
            this.$refs.editForm.validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true;
                        let para = Object.assign({}, this.editForm);

                        device_data_recipe_put(para).then((res) => {
                            this.begCode(res.code, res.message);

                            if (res.code == 0) {
                                this.editLoading = false;
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getUsers();
                            }
                        });
                    });
                }
            });
        },
        //新增
        addSubmit: function () {
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.addLoading = true;
                        //NProgress.start();
                        let para = Object.assign({}, this.addForm);

                        alarms_post_user(para).then((res) => {
                            this.begCode(res.code, res.message);
                            this.addLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: '提交成功',
                                type: 'success'
                            });
                            this.$refs['addForm'].resetFields();
                            this.addFormVisible = false;
                            this.getUsers();
                        });
                    });
                }
            });
        },
        selsChange: function (sels) {
            this.sels = sels;
        },
        //批量删除
        batchRemove: function () {
            var ids = this.sels.map(item => item.id).toString();
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                //NProgress.start();
                let para = {
                    dataId: sessionStorage.getItem('deviceDataRecipeId'),
                    idList: ids.split(',')
                };
                device_data_recipe_delete_body(para).then((res) => {
                    this.begCode(res.code, res.message);
                    this.listLoading = false;
                    //NProgress.done();
                    if (res.code == 0) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    }

                });
            }).catch(() => {

            });
        },
        alarms(index, row) {
            console.log(row)
            sessionStorage.setItem('deviceDataRecipeBodyId', row.id)
            this.$router.push({
                path: '/alarms/triggerslist'
            })
        },
        upload(file, fileList) {
            console.log("file", file);
            console.log("fileList", fileList);
            let files = {
                0: file.raw
            }
            if (this.custom_version == 0) {
                this.readExcel1(files);
            } else if (this.custom_version == 2) { //电量定制版
                this.readExcel2(files)
            }
        },
        readExcel1(files) { //表格导入
            var that = this;
            console.log(files);
            if (files.length <= 0) { //如果没有文件名
                return false;
            } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
                this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
                return false;
            }

            const fileReader = new FileReader();
            fileReader.onload = (ev) => {
                console.log('ev=====================>', ev)
                try {
                    const data = ev.target.result;
                    const workbook = XLSX.read(data, {
                        type: 'binary'
                    });
                    const wsname = workbook.SheetNames[0]; //取第一张表
                    const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
                    console.log(ws);
                    for (let i in ws) {
                        for (let k in this.unitlist) {
                            if (ws[i].单位 == this.unitlist[k].value) {
                                ws[i].unitType = this.unitlist[k].id
                            } else if (ws[i].单位 == this.unitlist[k].id) {
                                ws[i].单位 = this.unitlist[k].value
                                ws[i].unitType = this.unitlist[k].id
                            }
                        }
                        for (let j in this.dictlist) {
                            // console.log(this.dictlist)
                            // console.log(ws[i].数值类型)
                            if (ws[i].数值类型 == this.dictlist[j].remark) {
                                ws[i].数值类型 = this.dictlist[j].value
                            }
                        }
                        if (ws[i].读写 == "只读") {
                            ws[i].读写 = "0"
                        } else if (ws[i].读写 == "读写") {
                            ws[i].读写 = "1"
                        }

                        if (ws[i].数据类型 == "数值型") {
                            ws[i].数据类型 = "0"
                        } else if (ws[i].数据类型 == "开关型") {
                            ws[i].数据类型 = "1"
                        } else {
                            ws[i].数据类型 = "2"
                        }

                        if (ws[i].权限 == "公开") {
                            ws[i].权限 = '0'
                        } else if (ws[i].权限 == "1级") {
                            ws[i].权限 = '1'
                        } else if (ws[i].权限 == "2级") {
                            ws[i].权限 = '2'
                        } else if (ws[i].权限 == "3级") {
                            ws[i].权限 = '3'
                        } else if (ws[i].权限 == "4级") {
                            ws[i].权限 = '4'
                        } else if (ws[i].权限 == "5级") {
                            ws[i].权限 = '5'
                        } else if (ws[i].权限 == "6级") {
                            ws[i].权限 = '6'
                        } else if (ws[i].权限 == "7级") {
                            ws[i].权限 = '7'
                        } else if (ws[i].权限 == "8级") {
                            ws[i].权限 = '8'
                        } else if (ws[i].权限 == "9级") {
                            ws[i].权限 = '9'
                        } else if (ws[i].权限 == "10级") {
                            ws[i].权限 = '10'
                        } else if (ws[i].权限 == "不公开") {
                            ws[i].权限 = '11'
                        }

                        if (ws[i].是否展示 == "展示") {
                            ws[i].是否展示 = '1'
                        } else if (ws[i].是否展示 == "不展示") {
                            ws[i].是否展示 = '0'
                        }
                        let addForm = {
                            name: ws[i].数据点名称,
                            dataType: ws[i].数据类型.toString(),
                            register: ws[i].数据点地址.toString(),
                            registerLength: ws[i].registerLength ? ws[i].registerLength : "",
                            valueKind: ws[i].数值类型.toString(),
                            decimalAccuracy: ws[i].小数位数 ? ws[i].小数位数 : "0",
                            writeRead: ws[i].读写.toString(),
                            unit: ws[i].单位 ? ws[i].单位 : "",
                            unitType: ws[i].unitType ? ws[i].unitType : "",
                            ifVisible: "1",
                            fluxMode: '0',
                            remark: ws[i].描述 ? ws[i].描述 : "",
                            priority: 1,
                            refreshRate: 0,
                            fluxMode: "",
                            deviceRecipePictureGroupId: ws[i].图标组 ? ws[i].图标组 : "0",
                            dataRestrict: ws[i].权限,
                            ifSaveHistory: "1",
                            ifVisible: ws[i].是否展示 ? ws[i].是否展示 : "1",
                            integerAccuracy: ws[i].整数位数 ? ws[i].整数位数 : " "
                        }
                        let para = {
                            id: sessionStorage.getItem('deviceDataRecipeId'),
                            recipeBodyFormList: [addForm]
                        };
                        console.log(addForm)
                        console.log(para)
                        console.log(ws[i].name)
                        device_data_recipe_add_body(para).then((res) => {

                            this.begCode(res.code, res.message);
                            //NProgress.done();
                            if (res.code == 0) {
                                this.$message({
                                    message: '新增成功',
                                    type: 'success'
                                });
                                this.getUsers();
                            } else {
                                this.adderror = true
                            }

                        });

                    }


                    // that.peopleArr = [];//清空接收数据
                    // if(that.peopleArr.length == 1 && that.peopleArr[0].roleName == "" && that.peopleArr[0].enLine == ""){
                    //     that.peopleArr = [];
                    // }
                    //重写数据
                    try {

                    } catch (err) {
                        console.log(err)
                    }

                    this.$refs.upload.value = '';

                } catch (e) {

                    return false;
                }
            };
            fileReader.readAsBinaryString(files[0]);
        },
        readExcel2(files) { //表格导入
            var that = this;
            console.log(files);
            if (files.length <= 0) { //如果没有文件名
                return false;
            } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
                this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
                return false;
            }

            const fileReader = new FileReader();
            fileReader.onload = (ev) => {
                console.log('ev=====================>', ev)
                try {
                    const data = ev.target.result;
                    const workbook = XLSX.read(data, {
                        type: 'binary'
                    });
                    const wsname = workbook.SheetNames[0]; //取第一张表
                    const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
                    console.log(ws);
                    for (let i in ws) {
                        var register
                        if (ws[i].串口号 && !ws[i].数据点类型) {
                            ws[i].数据点类型 = 0
                        }
                        if (ws[i].数据点类型 == "保持数据点") {
                            ws[i].数据点类型 = 0
                        } else if (ws[i].数据点类型 == "线圈") {
                            ws[i].数据点类型 = 1
                        }
                        if (ws[i].串口号) {
                            register = ws[i].数据点地址.toString() + '-' + ws[i].串口号 + '#' + ws[i].数据点类型
                        } else if (!ws[i].串口号 && ws[i].数据点类型) {
                            register = ws[i].数据点地址.toString() + '#' + ws[i].数据点类型
                        } else {
                            register = ws[i].数据点地址.toString()
                        }
                        for (let k in this.unitlist) {
                            if (ws[i].单位 == this.unitlist[k].value) {
                                ws[i].unitType = this.unitlist[k].id
                            } else if (ws[i].单位 == this.unitlist[k].id) {
                                ws[i].单位 = this.unitlist[k].value
                                ws[i].unitType = this.unitlist[k].id
                            }
                        }
                        for (let j in this.dictlist) {
                            // console.log(this.dictlist)
                            // console.log(ws[i].数值类型)
                            if (ws[i].数值类型 == this.dictlist[j].remark) {
                                ws[i].数值类型 = this.dictlist[j].value
                            }
                        }
                        if (ws[i].读写 == "只读") {
                            ws[i].读写 = "0"
                        } else if (ws[i].读写 == "读写") {
                            ws[i].读写 = "1"
                        }

                        if (ws[i].数据类型 == "数值型") {
                            ws[i].数据类型 = "0"
                        } else if (ws[i].数据类型 == "开关型") {
                            ws[i].数据类型 = "1"
                        }

                        if (ws[i].权限 == "公开") {
                            ws[i].权限 = '0'
                        } else if (ws[i].权限 == "1级") {
                            ws[i].权限 = '1'
                        } else if (ws[i].权限 == "2级") {
                            ws[i].权限 = '2'
                        } else if (ws[i].权限 == "3级") {
                            ws[i].权限 = '3'
                        } else if (ws[i].权限 == "4级") {
                            ws[i].权限 = '4'
                        } else if (ws[i].权限 == "5级") {
                            ws[i].权限 = '5'
                        } else if (ws[i].权限 == "6级") {
                            ws[i].权限 = '6'
                        } else if (ws[i].权限 == "7级") {
                            ws[i].权限 = '7'
                        } else if (ws[i].权限 == "8级") {
                            ws[i].权限 = '8'
                        } else if (ws[i].权限 == "9级") {
                            ws[i].权限 = '9'
                        } else if (ws[i].权限 == "10级") {
                            ws[i].权限 = '10'
                        } else if (ws[i].权限 == "不公开") {
                            ws[i].权限 = '11'
                        }

                        if (ws[i].是否展示 == "展示") {
                            ws[i].是否展示 = '1'
                        } else if (ws[i].是否展示 == "不展示") {
                            ws[i].是否展示 = '0'
                        }
                        console.log(ws[i].数据点类型)
                        console.log(ws[i].串口号)
                        let addForm = {
                            name: ws[i].数据点名称,
                            dataType: ws[i].数据类型.toString(),
                            register: register,
                            registerLength: ws[i].registerLength ? ws[i].registerLength : "",
                            valueKind: ws[i].数值类型.toString(),
                            decimalAccuracy: ws[i].小数位数 ? ws[i].小数位数 : "0",
                            writeRead: ws[i].读写.toString(),
                            unit: ws[i].单位 ? ws[i].单位 : "",
                            unitType: ws[i].unitType ? ws[i].unitType : "",
                            ifVisible: "1",
                            fluxMode: '0',
                            remark: ws[i].描述 ? ws[i].描述 : "",
                            priority: 1,
                            refreshRate: 0,
                            fluxMode: "",
                            deviceRecipePictureGroupId: ws[i].图标组 ? ws[i].图标组 : "0",
                            dataRestrict: ws[i].权限,
                            ifSaveHistory: "1",
                            ifVisible: ws[i].是否展示 ? ws[i].是否展示 : "1",
                            integerAccuracy: ws[i].整数位数 ? ws[i].整数位数 : " "
                        }
                        let para = {
                            id: sessionStorage.getItem('deviceDataRecipeId'),
                            recipeBodyFormList: [addForm]
                        };
                        console.log(addForm)
                        console.log(para)
                        console.log(ws[i].name)
                        device_data_recipe_add_body(para).then((res) => {

                            this.begCode(res.code, res.message);
                            //NProgress.done();
                            if (res.code == 0) {
                                this.$message({
                                    message: '新增成功',
                                    type: 'success'
                                });
                                this.getUsers();
                            } else {
                                this.adderror = true
                            }

                        });

                    }
                    //重写数据
                    try {

                    } catch (err) {
                        console.log(err)
                    }

                    this.$refs.upload.value = '';

                } catch (e) {

                    return false;
                }
            };
            fileReader.readAsBinaryString(files[0]);
        },
    },
    mounted() {
        this.menubt = localStorage.getItem('menubt');
        this.getUsers();
        //
        let para = {
            pageSize: 999,
            pageNo: 1,
        }
        unit_query(para).then((res) => {
            if (res.code == 0) {
                this.unitlist = res.data.list
            }
        })

        let para1 = {
            name: 'valueKind',
            pageNo: 1,
            pageSize: 999,
        }
        dict_query(para1).then((res) => {
            if (res.code == 0) {
                this.dictlist = res.data.list;
            }
        })
    }
}
</script>

<style scoped>
.el-table {
    overflow-y: scroll;
    max-height: 500px;
}

.up-img {
    width: 10px;
    height: 10px;
    padding: 0 1px;
}</style>